package engine.newUi
{
	import engine.control.loading.MultLoader;
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.ObjectData;
	import engine.data.ResPath;
	import engine.data.RoleVo;
	import engine.data.View;
	import engine.data.ViewObject;
	import engine.logic.SceneTransfer;
	import engine.tip.TipsMainLogic;
	import engine.tip.tipItem.MarrowItem;
	import engine.ui.ActorPartnerGroup;
	
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.system.ApplicationDomain;
	import flash.text.TextField;
	
	import newx.StageInfo;
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.window.NxWindowEvent;
	import newx.com.loader.SwfLoader;

	/**
	 *洗髓主界面 
	 * @author yanghr
	 * 
	 */
	public class WashMarrowLogic
	{
		private static var _self:WashMarrowLogic;
		private const LEN:int=6;
		/**
		 *属性名 
		 */		
		private const DATAOBJ:String="dataobj";
		private const INDEX:String="index";
		private const EQUIP:String="item";
		private const TXT:String="titleTxt2";
		private const BOX:String="bbbox";
		private const LVL:String="infoTxt5";
		private const BIND:String="bind";
		private const BIND_LEVEL:String="bind_level";
		
		private const NORMAL:int	=	1;
		private const ROLL:int		=	2;
		private const DISABLE:int	=	3;
		private const DISABLE_SELECTED:int=4;
		
		public static function getInstance():WashMarrowLogic
		{
			if(_self==null)
			{
				_self=new WashMarrowLogic();
			}
			return _self;
		}
		private var _ui:WashMarrowUI;
		
		public  function get ui():WashMarrowUI
		{
			if(!_ui)
				_ui	=	new WashMarrowUI
			return _ui;
		}
		public function WashMarrowLogic()
		{
		}
		private const effectMap:Object={
			1:1,
			2:2,
			3:3,
			4:4,
			5:6,
			6:5
		}
		private const nameMap:Object={
			1:1,
			4:6,
			3:3,
			2:5,
			6:2,
			5:4
		};
		private var _bind:BindManage;
		private var _model:ModelLocator
		private var _role:RoleVo;
		private var _tip:TipsMainLogic;
		private var _dowash:DoMarrowLogic;
		
		private var _bindFlag:int=-1;
		private var _bindSavvyFlag:int=-1;
		private var _bindLvlFlag:int=-1;
		
		private var _linkB:Boolean=false;
		
		private var _rollMc:MovieClip;
		private var _initBeforeShow:Boolean;
		private var _initEffect:Boolean;
		
		private var _actorPartnerGroup:ActorPartnerGroup;
		
		private var _xisuilvl:int;
		
		public function  Init():void
		{
			_bind	= BindManage.getInstance();
			_model	= ModelLocator.getInstance();
			_role	= _model.scene.Role;
			_tip	= TipsMainLogic.instance;
			_dowash	= DoMarrowLogic.getInstance();
			changeLink(true);
			initName();
			var mc:MovieClip;
			_ui.bg.mouseEnabled = false;
			for (var i:int = 1; i <= LEN; i++) 
			{
				mc	= getLvlIcon(i);
				mc.addEventListener(MouseEvent.CLICK,clickLvlIconHandle);
				mc.addEventListener(MouseEvent.ROLL_OVER,iconTips);
				mc.addEventListener(MouseEvent.ROLL_OUT,iconOut);
				mc.buttonMode	= true;
				mc.mouseChildren= false;
				mc[INDEX]		= i;
				mc[BOX]			= new NxClip;
				mc.hasOwnProperty("mc")/*&&mc["mc"]*/?	mc["mc"].addChild(mc[BOX]):mc.addChild(mc[BOX]);
				indexChangeState(i,DISABLE)
				closure();
			}
			_actorPartnerGroup = new ActorPartnerGroup(_ui.actorGroup,setCurrentM);
//			resetRoleArr()
//			_currentSelectedM=ui.actorGroup.getItemByIndex(0);
//			_currentSelectedM.gotoAndStop(3);
			ui.remind.htmlStr	= StaticIni.getSwfLangStr("RandomPropertyTips_10");//RandomPropertyTips_10=点击按钮进行洗髓//"点击xxxxxxxxxx";
			function closure():void
			{
				var m:MovieClip		= mc;
				var lvl:int			= mc[INDEX];
				_tip.objRollshowTips(mc,t)
				_tip.objRollshowTips(getNameIcon(i),t)
					function t():String{
						var marrowTips:MarrowItem = new MarrowItem(_actorPartnerGroup.rollArr[_actorPartnerGroup.currentIndex], lvl)
						if(m.currentFrame == NORMAL || m.currentFrame == ROLL)
						{
							return  marrowTips.getWashMainStr()
						}
						else
						{
							return StaticIni.getSwfLangStr("RandomPropertyTips_1" + (3 + lvl));
						}
					}
			}
		}
		private function setCurrentM(value:MovieClip):void
		{
			currentSelectedM	= value;
		}
		private function changeLink(b:Boolean):void
		{
			ui.getLink.htmlText	= _tip.getUnderLineHtml(StaticIni.getSwfLangStr("RandomPropertyTips_21"), "a");
		}
		private function initName():void
		{
//			var i:int=1;
//			ui.pc["source"]=ResPath.PNG+"washMarrow_main.png";
//			while(ui.hasOwnProperty("pc"+i))
//			{
//				var nx:NxClip=	ui["pc"+i] as NxClip;
//				nx.source=ResPath.PNG+"xisui_yuan_"+nameMap[i]+".png";
//				i++
//			}
		}
		private function indexChangeState(index:int,state:int):void
		{
			var mc:MovieClip	= getLvlIcon(index);
			mc.gotoAndStop(state);
			if(state == DISABLE || state == DISABLE_SELECTED) {
				mc[BOX].visible	= false
			} else {
				mc[BOX].visible	= true;
			}
			var nameM:Sprite	= getNameIcon(index);
			nameM.visible		= mc[BOX].visible;
		}
		private function iconOut(e:Event):void
		{
			rollMc	= null;
		}
		private function iconTips(e:Event):void
		{
			var mc:MovieClip	= e.currentTarget as MovieClip;
			rollMc				= mc;
		}
		private function set rollMc(mc:MovieClip):void
		{
			if(_rollMc)
			{
				if(_rollMc.currentFrame == ROLL)
				{
//					_rollMc.gotoAndStop(NORMAL);
					indexChangeState(_rollMc[INDEX], NORMAL)
				}
				else if(_rollMc .currentFrame == DISABLE_SELECTED)
				{
					indexChangeState(_rollMc[INDEX], DISABLE)
				}
			}
			if(mc)
			{
				if(mc.currentFrame == NORMAL)
				{
					indexChangeState(mc[INDEX], ROLL)
				}
				else if(mc .currentFrame == DISABLE)
				{
					indexChangeState(mc[INDEX], DISABLE_SELECTED)
				}
			}
			_rollMc	= mc;
		}
		private function getNameIcon(index:int):Sprite
		{
			return ui["pc"+index];
		}
		private function getLvlIcon(index:int):MovieClip
		{
			return ui["lvl"+index]  //ui.bg["mc_"+index]
		}
		private function loadEffect():void
		{
//			_initEffect = true;
			var url:String = ResPath.SWF + "xisui.swf";
//			MultLoader.getInstance().load([url],true,initEffect);
//			function initEffect():void
//			{
				var m:MovieClip	= MultLoader.getInstance().getSourceByUrl(url);
				ResManager.SaveRes("xisui.swf",m);
				var domain:ApplicationDomain	= m.loaderInfo.applicationDomain;
				for (var i:int = 1; i <= LEN; i++) 
				{
					var mc:MovieClip			= getLvlIcon(i);
					var sourcTarget:MovieClip	= getClass("mcxisui_00" + effectMap[i]);
					mc[BOX].source				= sourcTarget;//"mcxisui_00"+i//
				}
				MultLoader.getInstance().deletAllSource();
				function getClass(str:String):DisplayObject
				{
					if(domain.hasDefinition(str))
					{
						var cls:Class			= domain.getDefinition(str) as Class;
						return new cls;
					}
					else
					{
						return null;
					}
				}
//			}
			
		}
		private function initBG():void
		{
//			ui.pc["source"]=ResPath.PNG+"washMarrow_main.png";
				const url:String	= ResPath.SWF + "washMarrow_main.swf";
				if(!_ui.pc["content"])
				{
					SwfLoader.StartLoad(url, null, f);
				}
				function f(mc:MovieClip,...args):void
				{
					_ui.pc["source"]	= mc;
				}
		}
		public function	BeforeShow():void
		{
			
			_initBeforeShow	= true;
			initBG();
//			ui.pc["source"]=ResPath.PNG+"washMarrow_main.png";
//			if(!_initEffect)
//			{
				loadEffect();
//			}
			_actorPartnerGroup.BeforeShow();
			addAllEventListener();
			refreshUI();
			_initBeforeShow	= false;
		}
		public function	AfterHide():void
		{
			_actorPartnerGroup.AfterHide();
			removeAllEventListener();
		}
		private function linkHandle(e:Event):void
		{
			if(ActivitesGroupLogic.getInstance().openUI(23)){
				SceneTransfer.getInstance().tranferTo("75051009");
			} else {
				NoticeUI.getInstance().showInfo(StaticIni.getSwfLangStr("RandomPropertyTips_33"));
			}
		}
		public function addAllEventListener():void
		{
			ui.getLink.addEventListener(MouseEvent.CLICK,linkHandle);
			if(_bindSavvyFlag == -1)
			{
				_bindSavvyFlag	=	_bind.BindProp(_role, "Savvy", this, "savvyCount");
			}
			if(_bindLvlFlag == -1)
			{
				_bindLvlFlag	=	_bind.BindProp(_role, "WLYBCurFloor", this, "marrowLvl");
			}
			ui.windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,close)
		}
		private function clickLvlIconHandle(e:Event):void
		{
			if(e.currentTarget.currentFrame == DISABLE || e.currentTarget.currentFrame == DISABLE_SELECTED) return;
			var view:ObjectData		= _actorPartnerGroup.currentData//_roleArr[currentSelectedM[INDEX]];
			var pos:int				= (view == _role) ? -1 : int(view.ObjKey);
			_xisuilvl				= int(e.currentTarget[INDEX]);
			DoMarrowLogic.getInstance().callForShow(view.GetPropertiesEx("ConfigID"), _xisuilvl, pos, view.GetPropertiesEx("Level"));
			
		}
		public function removeAllEventListener():void
		{
			if(_bindSavvyFlag != -1)
			{
				_bindSavvyFlag	=	_bind.UnbindProp(_role,"SavvyValue",_bindSavvyFlag)
			}
			if(_bindLvlFlag != -1)
			{
				_bindLvlFlag	=	_bind.UnbindProp(_role,"CheckPonit",_bindLvlFlag);
			}
		}
		/**
		 *洗髓等级 
		 * @param value
		 * 
		 */		
		public function set marrowLvl(value:int):void 
		{
			for (var i:int = 1; i <= LEN; i++) 
			{
				indexChangeState(i, (value>=i?NORMAL:DISABLE));
				if(value >= i)
					requestForP(i);
					
			}
		}
		public function requestALlMarrowData():void
		{
//			marrowLvl=_role.GetPropertiesEx("WLYBCurFloor");
//			checkAndSendRequest(
			var view:View	= _model.scene.GetView(View.VIEWPORT_PARTNER);
			view.getDataForEach(function (name:String,data:*):void
			{
				if(Number(name))
				{
					checkAndSendRequest(view.GetPropertiesEx(name),-1)
				}
			}
			)
			
		}
		/**
		 *请求数据 
		 * @param view  主角或者伙伴
		 * @param lvl	请求的洗髓等级（0代表请求所有的）
		 * 
		 */		
		public function checkAndSendRequest(view:ObjectData,lvl:int=0):void
		{
			if(lvl>	0)
			{
				send(lvl)
			}
			else
			{
				var l:int	= _role.GetPropertiesEx("WLYBCurFloor");
				for (var i:int = 1; i <= l; i++) 
				{
					send(i);
				}
			}
			function send(llvl:int):void
			{
				var pos:int		= (view ==_role) ? -1 : int(view.ObjKey);
				var arr:Array	= _dowash.serverArr;
				if(!DoMarrowLogic.getInstance().checkServerObj(view,pos))
					_dowash.requestForServerobj(llvl,pos)
			}
		}
		private function requestForP(lvl:int):void
		{
			var view:ObjectData		= _actorPartnerGroup.currentData//_roleArr[currentSelectedM[INDEX]];
			if(view)
			{
				checkAndSendRequest(view,lvl);
			}
		}
		public function set savvyCount(count:int):void
		{
			_ui.savvyTxT.htmlStr	= StaticIni.getSwfLangStrVar("RandomPropertyTips_9",[count]);
		}
		public function get currentSelectedM():MovieClip
		{
			return _actorPartnerGroup.currentMC;
		}
		public function get currentSeletedRole():ObjectData
		{
			return _actorPartnerGroup.currentData;
		}
		
		public function set currentSelectedM(value:MovieClip):void
		{
			refreshUI();
		}
		private function BindFunc(PropertiesName:String,PropertiesValue:*,pList:Array):void
		{
			var		Obj:Object	=	pList[0];
			var		value:*		=	pList[1];
			Obj[value](PropertiesValue);	
		}
		private function refreshUI():void
		{
			refreshBlind();
			marrowLvl	= _role.GetPropertiesEx("WLYBCurFloor");
			
			var i:int	= 1;
			while(ui.hasOwnProperty("pc"+i))
			{
				var nx:NxClip	= ui["pc"+i] as NxClip;
				nx.source		= ResPath.PNG + "xisui_yuan_" + nameMap[i]+ ".png";
				i++;
			}
			var view:ObjectData = _actorPartnerGroup.currentData;
			_ui.nameLab.htmlText = "<font color='#ffd100'>" + view.GetPropertiesEx("Name")+ "</font>";
			if(DoMarrowLogic.getInstance().created){
				var pos:int = (view == _role) ? -1 : int(view.ObjKey);
				DoMarrowLogic.getInstance().callForShow(view.GetPropertiesEx("ConfigID"), _xisuilvl, pos, view.GetPropertiesEx("Level"));
			}
		}
		private function refreshBlind():void
		{
			var obj:ObjectData	= _actorPartnerGroup.rollArr[_actorPartnerGroup.currentIndex]
			photo				= obj.GetPropertiesEx(ActorPropertyUI.MODEL);
		}
		public function set photo(value:String):void 
		{
			return ;
//			var url : String  = StageInfo.npcResPath + value + "_ani_0.swf";
//			if( photoMc != null && url == actorVisual.name)
//			{
//				return;
//			}
			var roleSkinIndex:int	=	0;
			var url:String	=	getUrl()
			url	=	ResPath.ACTORS + url;
			_ui.actorVisual.source =url
//			roleModel	=	ResPath.ACTORS + roleModel + value + ".swf";
//			ResManager.loadResNoSave(url, url, onPhotoLoad,[url]);
			function getUrl():String
			{
				var head:String;
				var tails:String;
				if(currentSelectedM[INDEX]!=0)
				{
					head	=	"npc_";
					tails	=	".swf";
					
				}
				else
				{
					roleSkinIndex	=	ModelLocator.getInstance().scene.Role.GetPropertiesEx("ClotheModel");
					roleSkinIndex	=	roleSkinIndex  == 0 ? 1 : roleSkinIndex;
					head	=	"role_";
					tails	=	"_"+roleSkinIndex+".swf";					
				}
				return head+value+tails;
			}
		}
		private function close(e:Event):void
		{
			_ui.showOrHide();
		}
	}
}